package chen.web.forum;

import java.lang.reflect.InvocationTargetException;

import chen.web.widget.Widget;
import chen.web.widget.book.Book;
import chen.web.widget.vote.Vote;

public class WidgetType {

	private static final Class<?>[] Classes = new Class<?>[]{
		Vote.class,
		Book.class
	};
	
	public static int getType(Class<? extends Widget> cls){
		for(int i=0; i<Classes.length; i++){
			if(cls.equals(Classes[i])){
				return i+1;
			}
		}
		return 0;
	}
	
	@SuppressWarnings("unchecked")
	public static Class<? extends Widget> getWidgetClass(int type){
		if(type < 1 || type > Classes.length){
			return null;
		}
		return (Class<? extends Widget>) Classes[type-1];
	}
	
	static Widget createWidget(int type, int widgetId){
		Widget widget = null;
		try {
			widget = (Widget) getWidgetClass(type).getConstructor(Integer.TYPE).newInstance(widgetId);
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}
		return widget;
	}

}
